import { Injectable, CanActivate, ExecutionContext, UseGuards } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { decode, sign, verify } from 'jsonwebtoken';

@Injectable()
export class AccessGuard implements CanActivate {
    constructor(
        private readonly reflector: Reflector
    ){}

    canActivate(context: ExecutionContext):boolean {
        //验证逻辑
        const request = context.switchToHttp().getRequest();
        const ctrl = context.getClass();
        //利用reflect metadata取得存取资源对应得方法
        const handler = context.getHandler();
        //取得header里的token信息
        let token;
        if(request.headers['authorization'] != undefined){
            // token = request.headers['authorization'].replace(/\s*/g,"").substr(6);
            token = request.headers['authorization']
        }else{
            // token没有直接返回false
            return false;
        }
        //验证token是否过期等
        if(verify(token,'secret'))
        {
            let userInfo = JSON.parse(JSON.stringify(decode(token)));
            //如果能查询到角色信息
            if(userInfo){
                console.log('当前登录用户Id为：',userInfo)
                return true
            }
            return false
        }
        else{
            return false;
        }
    }
}